﻿
(function ($) {

    $.fn.maxlength = function (o) {

        var defaults = {
            text: 'Left: @_@',
            auto: 1, // auto show hide
            meta: 'maxlength'
        };

        return this.each(function () {
            var me = $(this);
            if ($.data(me, 'maxlength'))
                return;
            else {
                $.data(me, 'maxlength', true);
                var s = $.extend({}, defaults, o || {});

                if (s.meta && $.metadata) {
                    var data = me.metadata();
                    $.extend(s, data[s.meta] || {});
                }

                var maxlength = s.maxlength || parseInt(me.attr('maxlength'));

                if (maxlength <= 0) return;

                var callback = $.isFunction(s.callback) ? s.callback : function () { };

                if (!s.target) {
                    s.target = $('<p class="length-counter" />').insertAfter(me);
                }

                $(s.target).html(s.text.replace('@_@', '<strong>'+maxlength+'</strong>'));

                if (s.auto)
                    $(s.target).hide();

                me.unbind('.maxlength').bind('keyup.maxlength change.maxlength keydown.maxlength', function () {
                    var _val = $(this).val();
                    if (_val.length > maxlength)
                        me.val(_val.substr(0, maxlength));
                    var l = me.val().length;
                    var left = maxlength - l;
                    $(s.target).show().html(s.text.replace('@_@', '<strong>' + left + '</strong>'));
                    return callback(l, left);
                });

                if (s.auto) {
                    me.bind('blur.maxlength', function () {
                        $(s.target).hide();
                    }).bind('focus.maxlength', function () {
                        $(s.target).show();
                    });
                }

            }


        });
    };

})(jQuery);